package com.slz3.business.frame.util.poi;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;

import java.io.ByteArrayOutputStream;
import java.util.List;

/**
 * Created by Administrator on 2017/5/24.
 */
public class ExcelUtils {
    /**
     * 创建工作簿
     * @param sheetName sheet名称
     * @param obj       数据
     * @param columnName 标题
     * @param createRow 创建行接口
     * @param <T>       数据类型
     * @return  工作簿
     */
    public static <T> HSSFWorkbook createWorkBook(String sheetName, List<T> obj, String columnName[], CreateRow<T> createRow){
        HSSFWorkbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet(sheetName);
        createRow.setColumnWidth(sheet, columnName.length);

        Row headRow = sheet.createRow(0);
        createRow.configHeadRowStyle(headRow);

        Font headFont = wb.createFont();
        CellStyle headCellStyle = wb.createCellStyle();
        createRow.configHeadRowCellStyle(headFont, headCellStyle);

        Font rowFont = wb.createFont();
        CellStyle oddCellStyle = wb.createCellStyle();
        CellStyle evenCellStyle = wb.createCellStyle();
        createRow.configRowCellStyle(rowFont, oddCellStyle, evenCellStyle);

        for (int i = 0; i < columnName.length; i ++){
            Cell cell = headRow.createCell(i);
            cell.setCellValue(columnName[i]);
            cell.setCellStyle(headCellStyle);
        }

        for (int i = 1; i <= obj.size(); i ++){
            Row row = sheet.createRow(i);
            createRow.configRowStyle(i, row);
            createRow.writeRow(row, obj.get(i - 1));
            for (int j = 0; j < row.getLastCellNum(); j ++){
                row.getCell(j).setCellStyle((i % 2 == 0) ? evenCellStyle : oddCellStyle);
            }
        }
        return wb;
    }

    public static <T> DataBuffer createWorkBook2DataBuffer(String sheetName, List<T> obj, String columnName[], CreateRow<T> createRow){
        try {
            HSSFWorkbook workBook = createWorkBook(sheetName, obj, columnName, createRow);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            workBook.write(baos);
            baos.flush();
            DataBufferFactory dataBufferFactory=new DefaultDataBufferFactory();
            return dataBufferFactory.wrap(baos.toByteArray());
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
